import { computed } from 'vue'
import { getAllKeywords, getKeywordType } from '../utils/sqlKeywords'

/**
 * SQL语法高亮组合式函数
 * @param {Object} options - 配置选项 
 * @returns {Object} 高亮相关的响应式数据和方法
 */
export default function useSqlHighlight(options = {}) {
  const {
    content = '',
    theme = 'default'
  } = options

  // 高亮规则 - 匹配模式和对应的CSS类名
  const highlightRules = [
    // SQL关键词
    {
      pattern: /\b(SELECT|FROM|WHERE|INSERT|UPDATE|DELETE|CREATE|DROP|ALTER|TABLE|INDEX|VIEW|DATABASE|SCHEMA|PROCEDURE|FUNCTION|TRIGGER|AND|OR|NOT|IN|EXISTS|BETWEEN|LIKE|IS|NULL|TRUE|FALSE|GROUP BY|ORDER BY|HAVING|DISTINCT|COUNT|SUM|AVG|MIN|MAX|JOIN|INNER JOIN|LEFT JOIN|RIGHT JOIN|FULL JOIN|CROSS JOIN|ON|USING|INT|INTEGER|VARCHAR|CHAR|TEXT|DATE|DATETIME|TIMESTAMP|DECIMAL|FLOAT|DOUBLE|BOOLEAN|BLOB|JSON|PRIMARY KEY|FOREIGN KEY|UNIQUE|NOT NULL|DEFAULT|CHECK|AUTO_INCREMENT)\b/gi,
      className: 'sql-keyword'
    },
    // 字符串
    {
      pattern: /'([^'\\]|\\.)*'/g,
      className: 'sql-string'
    },
    {
      pattern: /"([^"\\]|\\.)*"/g,
      className: 'sql-string'
    },
    // 数字
    {
      pattern: /\b\d+(\.\d+)?\b/g,
      className: 'sql-number'
    },
    // 注释
    {
      pattern: /--.*$/gm,
      className: 'sql-comment'
    },
    {
      pattern: /\/\*[\s\S]*?\*\//g,
      className: 'sql-comment'
    },
    // 操作符
    {
      pattern: /[=<>!]+|[+\-*/%]/g,
      className: 'sql-operator'
    },
    // 标识符（表名、列名等）
    {
      pattern: /\b[a-zA-Z_][a-zA-Z0-9_]*\b/g,
      className: 'sql-identifier'
    }
  ]

  /**
   * 高亮SQL文本
   * @param {string} text - 要高亮的SQL文本
   * @returns {string} 高亮后的HTML
   */
  const highlightSql = (text) => {
    if (!text) {
      return ''
    }

    let result = text
    
    // 转义HTML字符
    result = result
      .replace(/&/g, '&amp;')
      .replace(/</g, '&lt;')
      .replace(/>/g, '&gt;')
      .replace(/"/g, '&quot;')
      .replace(/'/g, '&#39;')

    // 应用高亮规则
    highlightRules.forEach(rule => {
      result = result.replace(rule.pattern, (match) => {
        return `<span class="${rule.className}">${match}</span>`
      })
    })

    // 处理换行
    result = result.replace(/\n/g, '<br>')
    
    return result
  }

  // 高亮HTML内容
  const highlightedHtml = computed(() => {
    return highlightSql(content.value || '')
  })

  // 获取单词的样式类名
  const getWordClassName = (word) => {
    if (isKeyword(word)) {
      return 'sql-keyword'
    }
    
    if (/^\d+(\.\d+)?$/.test(word)) {
      return 'sql-number'
    }
    
    return 'sql-identifier'
  }

  // 检查是否为关键词
  const isKeyword = (word) => {
    return getAllKeywords().includes(word.toUpperCase())
  }

  return {
    highlightedHtml,
    highlightSql,
    getWordClassName,
    isKeyword
  }
} 